package com.woniuxy.creditsystem.systemmag.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.creditsystem.annos.MyLog;
import com.woniuxy.creditsystem.common.bean.*;
import com.woniuxy.creditsystem.common.bean.ResultMsg;
import com.woniuxy.creditsystem.common.mapper.DownloadMapper;
import com.woniuxy.creditsystem.common.mapper.SystemLogMapper;
import com.woniuxy.creditsystem.systemmag.service.IDownloadService;
import com.woniuxy.creditsystem.systemmag.service.ISystemLogService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 角色的增、删、查、改
 * @author hejie
 */
@Service
@Transactional(readOnly = true)
public class SystemLogServiceImpl implements ISystemLogService {

    @Resource
    private SystemLogMapper systemLogMapper;
    //用来把导出的excel信息，存储到download_info表中。供“下载中心”中下载该excel文件
    @Resource
    private IDownloadService downloadServiceImpl;

    /**
     * 新增 系统日志对象
     * @author hejie
     * @param systemLogInfo
     * @return
     */
//    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class,readOnly = false)
    @Transactional(isolation = Isolation.REPEATABLE_READ,readOnly = false)
    @Override
    public int saveSystemLogBean(SystemLogInfo systemLogInfo) {
        return systemLogMapper.saveSystemLogBean(systemLogInfo);
    }



    /**
     * 分页查询（同时具有 模糊查询功能--动态sql）
     * @author hejie
     * @param systemLogInfo 条件
     * @return
     */
    @Override
    public PageInfo<SystemLogInfo> findAllByParams(int pageNum, int pageSize, SystemLogInfo systemLogInfo, String excuteTimeStr) {
        if (systemLogInfo.getUserInfo()==null){
            return PageHelper.startPage(pageNum,pageSize).
                    doSelectPageInfo(()->systemLogMapper.findAllByParamsIfUserEmpty(systemLogInfo,excuteTimeStr));
        }else {
            return PageHelper.startPage(pageNum,pageSize).
                    doSelectPageInfo(()->systemLogMapper.findAllByParamsIfUserNotEmpty(systemLogInfo,excuteTimeStr));
        }


    }

    /**
     * 删除一个RoleInfo
     * @author hejie
     * @param id
     * @return
     */
    @MyLog(value = "删除一个系统日志记录")
    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    @Override
    public int deleteSystemLogInfo(Long id) {
//        System.out.println(1/0);
        return systemLogMapper.deleteSystemLogInfo(id);
    }

    /**
     * 把页面传回来的table数据，写入到excel文件中
     * @author hejie
     * @param tableDataJson
     * @return
     */
    @MyLog(value = "POI，导出账号系统日志结果为excel文件")
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
//    @Transactional(readOnly = true)
   public ResultMsg write2excel(List<SystemLogInfo> tableDataJson, String path, String simpleFileNameUserSet) throws IOException{
        if (tableDataJson==null){
            return new ResultMsg(201,"页面表格内容为空，没有数据可以导出！",null);
        }


        //创建表对象，即工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //第一个sheet对象demo1
        HSSFSheet sheet = workbook.createSheet("demo1");
        //行对象
        HSSFRow row = sheet.createRow(0);

        //单元格对象
        HSSFCell cell0 = row.createCell(0);
        cell0.setCellValue("操作用户");
        HSSFCell cell1 = row.createCell(1);
        cell1.setCellValue("执行时间");
        HSSFCell cell2 = row.createCell(2);
        cell2.setCellValue("操作");
        HSSFCell cell3 = row.createCell(3);
        cell3.setCellValue("请求方法");
        HSSFCell cell4 = row.createCell(4);
         cell4.setCellValue("执行时长（毫秒）");
        HSSFCell cell5 = row.createCell(5);
        cell5.setCellValue("IP地址");
        HSSFCell cell6 = row.createCell(6);
        cell6.setCellValue("执行结果");

        //解决日期显示不正常的问题：给第1行、第2列单元格写入日期
        //用Excel表对象获取CreationHelper对象
        CreationHelper createHelper = workbook.getCreationHelper();
        //用Excel表对象创建CellStyle对象
        CellStyle cellStyle = workbook.createCellStyle();
        //给cellStyle对象设置Date格式
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        for (int i=0; i<tableDataJson.size(); i++){
            //行对象
            HSSFRow r = sheet.createRow(1+i);
//            for (int j=0; j<7; j++){
                //单元格对象
                //0.操作用户
                HSSFCell cellOptUserName = r.createCell(0);
                cellOptUserName.setCellValue(tableDataJson.get(i).getUserInfo().getUserName());

                //1.执行时间
                HSSFCell cellExcuteTime = r.createCell(1);
                //设置 “Date”类型的显示格式
                cellExcuteTime.setCellStyle(cellStyle);
                cellExcuteTime.setCellValue(tableDataJson.get(i).getExcuteTime());

                //2.操作
                HSSFCell cellOperation = r.createCell(2);
                cellOperation.setCellValue(tableDataJson.get(i).getOperation());

                //3.请求方法
                HSSFCell cellRequestMethod = r.createCell(3);
                cellRequestMethod.setCellValue(tableDataJson.get(i).getRequestMethod());

                //4.执行时长
                HSSFCell cellExcuteTimeConsume = r.createCell(4);
                cellExcuteTimeConsume.setCellValue(tableDataJson.get(i).getExcuteTimeConsume());

                //5.ip地址
                HSSFCell cellIp = r.createCell(5);
                cellIp.setCellValue(tableDataJson.get(i).getIp());

                //6.执行结果
                HSSFCell cellExecuteResult = r.createCell(6);
                String executeResult="";
                if (tableDataJson.get(i).getExecuteResult()==1){
                    executeResult="成功";
                }else {
                    executeResult="失败";
                }
                cellExecuteResult.setCellValue(executeResult);

//            }
        }

        FileOutputStream os = null;
        //fileName是excel文件名字：包含了“.excel”，该路径需要存到的“download_info表”的“file_path”字段
        //不含后缀名“.xls”
        String simpleFileName= "系统日志" + System.currentTimeMillis();
        //如果用户要自己设置文件名字，就要传入非空的名字
        if (simpleFileNameUserSet!=null && !("".equals(simpleFileNameUserSet))){
            simpleFileName=simpleFileNameUserSet;
        }
        String filePathName = path +File.separator + simpleFileName + ".xls";
        File file=new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        try {
            os = new FileOutputStream(filePathName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //		workbook1.write(os);
        try {
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        os.flush();
        os.close();

        //把 文件名+后缀 放到ResultMsg的data中返回，方便：“新增下载”时，能够直接自动开始下载，而不用费力去“下载中心”点击“下载”
        ResultMsg resultMsg=  new ResultMsg(200,"页面表格数据已经写入到"+filePathName,simpleFileName + ".xls");

        //把当前“下载中心”记录写入到数据库download_info
        //simpleFileName是excel名字，不含后缀名 （存储到download_info表中的excel文件名是 simpleFileName.xsl，simpleFileName是变量）
        downloadServiceImpl.saveExcelInfo2downloadInfo(simpleFileName);
        return resultMsg;
    }
}
